import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from '@/components/ui/accordion';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import config from '@/config';
import { AvaliableItem, getAvaliableCategoryReduction } from '@/lib/gigaAvaliable';
import { cn } from '@/lib/utils';
import { useGigaNotPersisStore } from '@/store/gigaNotPersist';
import { format } from 'date-fns';
import { CalendarIcon } from 'lucide-react';
import { useId } from 'react';
import { toast } from 'sonner';
import useLocalStorage from '../hook/useLocalStorage';

type Props = {
  children?: React.ReactNode;
  className?: string;
};
export default function AvaliableReductionStatistics({ children, className, ...props }: Props) {
  const [startDate, setStartDate] = useState<Date | undefined>(
    new Date(new Date().getTime() - 1000 * 60 * 60 * 24),
  );
  const [endDate, setEndDate] = useState<Date | undefined>(new Date(new Date().getTime()));
  const [storeValue, setStoreValue] = useLocalStorage<{
    limit: number;
    prefixSkuInfoFilter: string;
  }>('avaliable-reduction-statistics', {
    limit: 10,
    prefixSkuInfoFilter: 'B,T',
  });
  const [avaliableReduction, setAvaliableReduction] = useState<Record<string, AvaliableItem[]>>({});
  const categoryTree = useGigaNotPersisStore((state) => state.categoryTree);
  const [expandedItems, setExpandedItems] = useState<string[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  async function getAvaliableReduction() {
    if (!startDate || !endDate) {
      toast.error('没有设置时间范围');
      return;
    }
    const sortCategoryNames = Object.keys(categoryTree).sort((itemA, itemB) => {
      return itemA.localeCompare(itemB);
    });
    for (const sortCategoryName of sortCategoryNames) {
      // 获取一定时间范围内,库存的减少量
      // console.log(startDate, endDate);
      let avaliableCategoryReduction = await getAvaliableCategoryReduction(
        startDate.getTime(),
        endDate.getTime(),
        sortCategoryName,
      );

      // 过滤掉前缀
      avaliableCategoryReduction = avaliableCategoryReduction.filter((item) => {
        const prefixList = storeValue.prefixSkuInfoFilter.split(',').map((prefex) => {
          return prefex.trim();
        });
        return !prefixList.some((prefex) => {
          return item.skuInfo.startsWith(prefex);
        });
      });

      avaliableCategoryReduction = avaliableCategoryReduction
        .sort((itemA, itemB) => {
          return itemB.reduction - itemA.reduction;
        })
        .slice(0, storeValue.limit);
      // console.log(avaliableCategoryReduction);
      setAvaliableReduction((prev) => {
        return {
          ...prev,
          [sortCategoryName]: avaliableCategoryReduction,
        };
      });
      if (avaliableCategoryReduction.length > 0) {
        setExpandedItems((prev) => [...prev, sortCategoryName]);
      }
    }
  }
  const id = useId();
  return (
    <div className={className} {...props}>
      <Sheet modal={false}>
        <SheetTrigger asChild>{children}</SheetTrigger>
        <SheetContent
          className="!max-w-[60vw] flex flex-col w-auto"
          style={{
            zIndex: config.sheetZIndex,
          }}
        >
          <SheetHeader>
            <SheetTitle>库存变化量统计</SheetTitle>
            <span className="text-xs">
              (计算方式是时间段内最大库存减去最少库存,和表格中的减少量计算不同,表格是两个时间中的最新库存量相减)
            </span>
          </SheetHeader>
          <div className="mt-2">
            <div className="flex items-center">
              <span className="mr-3">时间范围: </span>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    size={'sm'}
                    variant={'outline'}
                    className={cn(
                      'justify-start text-left font-normal',
                      !startDate && 'text-muted-foreground',
                    )}
                  >
                    <CalendarIcon />
                    {startDate ? format(startDate, 'PPP') : <span>选择开始范围</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent
                  className="w-auto p-0"
                  style={{
                    zIndex: config.alertDialogZIndex,
                  }}
                >
                  <Calendar mode="single" selected={startDate} onSelect={setStartDate} />
                </PopoverContent>
              </Popover>
              <span className="mx-1">~</span>
              <Popover>
                <PopoverTrigger asChild>
                  <Button
                    size={'sm'}
                    variant={'outline'}
                    className={cn(
                      'justify-start text-left font-normal',
                      !endDate && 'text-muted-foreground',
                    )}
                  >
                    <CalendarIcon />
                    {endDate ? format(endDate, 'PPP') : <span>选择结束范围</span>}
                  </Button>
                </PopoverTrigger>
                <PopoverContent
                  className="w-auto p-0"
                  style={{
                    zIndex: config.alertDialogZIndex,
                  }}
                >
                  <Calendar mode="single" selected={endDate} onSelect={setEndDate} />
                </PopoverContent>
              </Popover>
              <div className="flex gap-2 items-center py-2 ml-3">
                <Label className="whitespace-nowrap" htmlFor={id + '-day-interval'}>
                  前缀货号过滤:
                </Label>
                <Input
                  value={storeValue.prefixSkuInfoFilter}
                  onChange={(event) => {
                    setStoreValue((prev) => {
                      return {
                        ...prev,
                        prefixSkuInfoFilter: event.target.value,
                      };
                    });
                  }}
                  id={id + '-day-interval'}
                  className="h-10 w-[120px] rounded-md border border-input px-3 py-2"
                />
              </div>
            </div>
            <div className="mt-2 flex items-center">
              <div className="flex gap-2 items-center py-2">
                <Label className="whitespace-nowrap" htmlFor={id + '-limit'}>
                  每一个分类下减少量返回数量:
                </Label>
                <Input
                  value={storeValue.limit}
                  type="number"
                  onChange={(event) => {
                    setStoreValue((prev) => {
                      return {
                        ...prev,
                        limit: +event.target.value,
                      };
                    });
                  }}
                  id={id + '-limi'}
                  className="h-10 w-auto rounded-md border border-input px-3 py-2"
                />
              </div>
              <Button
                onClick={async () => {
                  if (isRunning) {
                    toast.info('正在统计中...');
                  }
                  setIsRunning(true);
                  await getAvaliableReduction();
                  setIsRunning(false);
                  toast.success('统计完成');
                }}
                size="sm"
                className="ml-auto hover:bg-[#337AB7] bg-[#428BCA]"
              >
                开始统计{isRunning ? '(统计中...)' : ''}
              </Button>
            </div>
          </div>
          <div className="grow overflow-auto">
            <div>{`${startDate?.toLocaleString()} 到 ${endDate?.toLocaleString()} 的库存变化量`}</div>
            <Accordion
              type="multiple"
              className="w-full"
              value={expandedItems}
              onValueChange={setExpandedItems}
            >
              {Object.keys(avaliableReduction).map((categoryName, index) => {
                return (
                  <div key={categoryName} className="leading-loose py-1">
                    <AccordionItem value={categoryName}>
                      <AccordionTrigger className="flex items-center gap-2 justify-start py-0 !flex-nowrap">
                        <div className="whitespace-nowrap">{categoryName}</div>
                      </AccordionTrigger>
                      <AccordionContent className="pl-4">
                        {avaliableReduction[categoryName].map((item) => {
                          return (
                            <div key={item.skuInfo} className="my-1">
                              <span>{item.skuInfo}: </span>
                              <span className="text-green-700">{`(${item.reduction}/${item.maxAvaliable}-${item.minAvaliable})`}</span>
                            </div>
                          );
                        })}
                      </AccordionContent>
                    </AccordionItem>
                  </div>
                );
              })}
            </Accordion>
          </div>
        </SheetContent>
      </Sheet>
    </div>
  );
}
